import  serial
import asyncio
from time import time
class RemoteCtl:
    def __init__(self,port,baidrate=9600,loop=None):
        self.__ser=serial.Serial(port=port,baudrate=9600,timeout=0,inter_byte_timeout=0.1)
        if loop:
            self.__loop=loop
        else:
            self.__loop=asyncio.get_event_loop()
        self.__key=0
        self.__pre_time=time()
        self.__event=asyncio.Event()
        self.__future=asyncio.Future()
        asyncio.ensure_future(self._start_monitor())
    async def _start_monitor(self):
        def callbak():
            buf=self.__ser.read(3)
            if len(buf)==3 :#and buf[0:2]==b"\x00\xff":
                self.__key=int(buf[2])
                self.__event.set()
        self.__loop.add_reader(self.__ser.fileno(),callbak)
        await  self.__future
    def close(self):
        self.__loop.remove_reader(self.__ser.fileno())
        self.__ser.close()
        self.__future.set_result(0)
    async def key(self,block):
        result=0
        if block:
            await self.__event.wait()
            self.__event.clear()
            result=self.__key
        elif self.__event.is_set():
                self.__event.clear()
                result=self.__key
        if result:
            if (time()-self.__pre_time)<0.4:
                return 0
            else:
                self.__pre_time=time()
                return result
                

if  __name__=='__main__':
    #test
    async def  main(remotectl,loop):
        while 1:
            key=await remotectl.key(True)
            if key==0:
                await asyncio.sleep(0)
                continue
            if key==5:break
            print(key)
            await asyncio.sleep(0)
        remotectl.close()
        loop.stop()

    loop=asyncio.get_event_loop()
    ser=RemoteCtl("/dev/ttyTHS1",loop)
    asyncio.ensure_future(main(ser,loop))
    try:
        loop.run_forever()
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()


